<?php

use think\Db;
// 应用公共文件
/**
 * 发送邮件
 * @param string $mail_to  收件人，可多个，以,分隔的字符串
 * @param string $mailsubject  邮件标题
 * @param string $mailbody 邮件正文
 * @return bool
 */
function send_mail($mail_to, $mailsubject, $mailbody){
	vendor('PHPMailer.PHPMailerAutoload');
    $email_config = model('system')->getValue('email_config');
	$address = explode(',',$mail_to);
    $mail = new \PHPMailer; //https://github.com/PHPMailer/PHPMailer
    //$mail->SMTPDebug = 3;                         // 启用详细的调试输出
    $mail->isSMTP();                                // 设置邮件程序使用SMTP
    $mail->Host = $email_config['smtp'];                       // 指定主服务器和备份SMTP服务器
    $mail->SMTPAuth = true;                         // 启用SMTP验证
    $mail->CharSet = "UTF-8";                       // 设置邮件编码
    $mail->Username = $email_config['loginname'];               // SMTP username，发件箱
    $mail->Password = $email_config['password'];               // SMTP password，发件箱密码
	$mail->SMTPSecure = 'ssl';                            // Enable TLS encryption, `ssl` also accepted
    $mail->Port = 465;                                    // TCP port to connect to
    $mail->setFrom($email_config['loginname'],$email_config['sender']);                 //发件人
	foreach($address as $v){
		$mail->addAddress($v);                    // 添加收件人,名称是可选的
	}
    $mail->isHTML(true);                            // 将电子邮件格式设置为HTML
    $mail->Subject = $mailsubject;
    $mail->Body    = $mailbody;
    if(!$mail->send()) {
        return false;		//return 'Mailer Error: ' . $mail->ErrorInfo;
    } else {
        return true;
    }
}

/**
 * 把返回的数据集转换成Tree
 * @param array $list 要转换的数据集
 * @param string $pid parent标记字段
 * @param string $level level标记字段
 * @return array
 */
function list_to_tree($list, $pk='id', $pid = 'pid', $child = '_child', $root = 0) {
    // 创建Tree
    $tree = array();
    if(is_array($list)) {
        // 创建基于主键的数组引用
        $refer = array();
        foreach ($list as $key => $data) {
            $refer[$data[$pk]] =& $list[$key];
        }
        foreach ($list as $key => $data) {
            // 判断是否存在parent
            $parentId =  $data[$pid];
            if ($root == $parentId) {
                $tree[] =& $list[$key];
            }else{
                if (isset($refer[$parentId])) {
                    $parent =& $refer[$parentId];
                    $parent[$child][] =& $list[$key];
                }
            }
        }
    }
    return $tree;
}

/**
 * 数组层级缩进转换
 * @param array $array 源数组
 * @param string $table
 * @param int $pid
 * @param int $level
 * @return array
 */
function array2level($array, $table = 'nav', $pid = 0, $level = 1)
{
    static $list = [];
    foreach ($array as $v) {
        if ($v['pid'] == $pid) {
            $v['level'] = $level;
            $son = Db::name($table)->where(['pid'=>$v['id']])->count('id');
            $son?$v['son'] = true:$v['son'] = false;
            $list[]     = $v;
            array2level($array, $table, $v['id'], $level + 1 );
        }
    }

    return $list;
}

/**平均分配红包
 * @param $money
 * @param $num
 * @param array $arr
 * @param int $conversion_val
 * @return array
 */
function average_money($money, $num, $arr=[], $conversion_val=1)
{
    $money = $money * 100;
    $arr_sum = 0;//保存数组和
    if (count($arr) > 0) {// 随机分配，会调用此方法将剩余的钱分掉，此数组为随机分配后的结果
        foreach ($arr as $k=>$v)  {
            $arr[$k] = $v * 100 / $conversion_val;// 如果单位有变化这调整一下，一直以分为单位处理数据
        }
        $arr_sum = array_sum($arr);// 统计随机分配已经分配了总钱数
    } else {
        for ($i=0; $i<$num; $i++) {
            $arr[] = 0;// 初始化每个人的数组，兼容下边循环处理部分
        }
    }
    $add_money = $money - $arr_sum;
    // 如果总钱数和之前随机分配的数组的总和差值为0，就说明随机分配已经将钱全部分出去了，就不需要再平均分配处理了
    if ($add_money == 0) {
        return $arr;
    }
    // 先把剩余的能均分的部分均分一下，然后若再有剩余，则从前到后，注意分配
    for ($i = 0; $i < $num; $i++) {
        $arr[$i] = $arr[$i] + floor($add_money / $num);// 如果之前有随机分配，则是将剩余的钱平均追加入随机分配的值里
    }
    $arr_sum = array_sum($arr);// 分配后，求和，用于修正最后剩余的零钱
    // 如果还有剩余，这部分说明每人一分都不够，就从头开始没人一分的分下去，直到分完为止
    $odd_money = bcsub($money, $arr_sum, 0);// 针对钱的计算，建议使用bc函数，普通的计算方法有误差
    $i = 0;
    while ($odd_money >= 1) {
        $arr[$i] = $arr[$i] + 1;// 每人加1分钱
        $odd_money = $odd_money - 1;// 剩余的金额，每分掉一个人，就减1分钱
        $i++;
    }
    return $arr;
}

function array2levels($array, $pid = 0, $level = 1)
{
        static $list = [];
        foreach ($array as $v) {
            if ($v['parentid'] == $pid) {
                $v['level'] = $level;
                $list[] = $v;
                array2levels($array, $v['id'], $level + 1);
            }
        }
        return $list;
    }

/**
 * 构建层级（树状）数组
 * @param array  $array          要进行处理的一维数组，经过该函数处理后，该数组自动转为树状数组
 * @param string $pid_name       父级ID的字段名
 * @param string $child_key_name 子元素键名
 * @return array|bool
 */
function array2tree(&$array, $pid_name = 'pid', $child_key_name = 'children')
{
    $counter = array_children_count($array, $pid_name);
    if (!isset($counter[0]) || $counter[0] == 0) {
        return $array;
    }
    $tree = [];
    while (isset($counter[0]) && $counter[0] > 0) {
        $temp = array_shift($array);
        if (isset($counter[$temp['id']]) && $counter[$temp['id']] > 0) {
            array_push($array, $temp);
        } else {
            if ($temp[$pid_name] == 0) {
                $tree[] = $temp;
            } else {
                $array = array_child_append($array, $temp[$pid_name], $temp, $child_key_name);
            }
        }
        $counter = array_children_count($array, $pid_name);
    }

    return $tree;
}

/**
 * 子元素计数器
 * @param array $array
 * @param int   $pid
 * @return array
 */
function array_children_count($array, $pid)
{
    $counter = [];
    foreach ($array as $item) {
        $count = isset($counter[$item[$pid]]) ? $counter[$item[$pid]] : 0;
        $count++;
        $counter[$item[$pid]] = $count;
    }

    return $counter;
}

/**
 * 把元素插入到对应的父元素$child_key_name字段
 * @param        $parent
 * @param        $pid
 * @param        $child
 * @param string $child_key_name 子元素键名
 * @return mixed
 */
function array_child_append($parent, $pid, $child, $child_key_name)
{
    foreach ($parent as &$item) {
        if ($item['id'] == $pid) {
            if (!isset($item[$child_key_name]))
                $item[$child_key_name] = [];
            $item[$child_key_name][] = $child;
        }
    }

    return $parent;
}

/**
 * 不区分大小写的in_array实现
 * @param mixed $value 待搜索的值。
 * @param array $array 待搜索的数组。
 * @return boolean  如果找到则返回 TRUE，否则返回 FALSE。
 */
function in_array_case($value,$array){
    return in_array(strtolower($value),array_map('strtolower',$array));
}

/**
 * 截取中文字符串
 * @param $str  待处理字符串
 * @param int $start    开始位置
 * @param $length   长度
 * @param string $charset   字符集
 * @param bool $suffix  增加...
 * @return string
 */
function msubstr($str, $start=0, $length, $charset="utf-8", $suffix=true){
    $str = strip_tags($str);//去除html和php标签
    //$str = preg_replace('/\s/','',$str);//去除\s
    if(function_exists("mb_substr")){
        $slice= mb_substr($str, $start, $length, $charset);
    }elseif(function_exists('iconv_substr')) {
        $slice= iconv_substr($str,$start,$length,$charset);
    }else{
        $re['utf-8'] = "/[x01-x7f]|[xc2-xdf][x80-xbf]|[xe0-xef][x80-xbf]{2}|[xf0-xff][x80-xbf]{3}/";
        $re['gb2312'] = "/[x01-x7f]|[xb0-xf7][xa0-xfe]/";
        $re['gbk'] = "/[x01-x7f]|[x81-xfe][x40-xfe]/";
        $re['big5'] = "/[x01-x7f]|[x81-xfe]([x40-x7e]|xa1-xfe])/";
        preg_match_all($re[$charset], $str, $match);
        $slice = join("",array_slice($match[0], $start, $length));
    }    
    $fix='';
    if(strlen($slice) < strlen($str)){
        $fix='...';
    }
    return $suffix ? $slice.$fix : $slice;
}

/**
 * 生成16位随机数
 * @param int $length 生成字符串长度
 * @return string
 */
function createNonceStr($length = 16) {
    $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
    $str = "";
    for ($i = 0; $i < $length; $i++) {
        $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
    }
    return $str;
}

/**
 * 获取面包屑
 * @param $id   当前导航id
 * @param string $str   字符串引用值
 * @return string   返回面包屑
 */
function crumbs($id,&$str=''){
    $nav = db('nav')->field('id,pid,name')->find($id);
    $str = '><a href="'.url($nav['link'],$nav['pid']==0?['fid'=>$nav['id']]:['nid'=>$nav['id']]).'">'.$nav['name'].'</a>'.$str;
    if($nav['pid']!=0) crumbs($nav['pid'],$str);
    return $str;
}

/**
 * 获取当前导航的最顶层导航id
 * @param $id   当前导航id
 * @return mixed    返回最顶层id
 */
function base_pid($id){
    $nav = db('nav')->field('id,pid')->find($id);
    while ($nav['pid']!=0){
        $nav = db('nav')->field('id,pid')->find($nav['pid']);
    }
    return $nav['id'];
}

/**
 * 根据键给二维数组分组
 * @param array $arr  二维数组
 * @param mixed $key  键
 * @return array    返回分组后数组
 */
function array_group_by($arr, $key)
{
    $grouped = [];
    foreach ($arr as $value) {
        $grouped[$value[$key]][] = $value;
    }
    if (func_num_args() > 2) {
        $args = func_get_args();
        foreach ($grouped as $key => $value) {
            $parms = array_merge([$value], array_slice($args, 2, func_num_args()));
            $grouped[$key] = call_user_func_array('array_group_by', $parms);
        }
    }
    return $grouped;
}

/**
 * curl GET
 * @param $url
 * @return mixed
 */
function httpGet($url){
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_TIMEOUT, 50);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    $res = curl_exec($curl);
    curl_close($curl);
    return $res;
}

/**
 * curl POST
 * @param $url
 * @param $data
 * @return mixed
 */
function httpPost($url,$data){
    //以上方式获取到的数据是json格式的
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    // post数据
    curl_setopt($ch, CURLOPT_POST, 1);
    // post的变量
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    $output = curl_exec($ch);
    curl_close($ch);
    return $output;
}

/**
 * 转换特殊HTML实体
 * @param string $str  输入字符
 * @param string $enc   字符编码
 * @return string   返回转换后的字符
 */
function HShtmlspecialchars($str,$enc='UTF-8'){
    return htmlspecialchars(trim($str), ENT_QUOTES, $enc);   //UTF-8防止中文乱码
}

/**
 * 用于模型中返回处理结果（验证及执行的判断）
 * @param int $code     返回码，1成功，0失败
 * @param string $msg 提示语
 * @param string $url 需跳转的url
 * @return array
 * @internal param string $data 返回数据
 */
function ajax_return($code,$msg,$url = ''){
    if ($url=='' && !is_null($_SERVER['HTTP_REFERER']) && $code==1) {   //成功时有跳转url，失败仅提示
        $url = $_SERVER['HTTP_REFERER'];
    } elseif ('' !== $url){
        $url = url($url);
    }
    $result = ['code' => $code, 'msg'  => $msg, 'url'  => $url];
    return $result;
}

/**
 * 二维数组排列组合
 * @param array $options
 * @return array
 */
function combination(array $options)
{
    $rows = [];

    foreach ($options as $option => $items) {
        if (count($rows) > 0) {
            // 2、将第一列作为模板
            $clone = $rows;

            // 3、置空当前列表，因为只有第一列的数据，组合是不完整的
            $rows = [];

            // 4、遍历当前列，追加到模板中，使模板中的组合变得完整
            foreach ($items as $item) {
                $tmp = $clone;
                foreach ($tmp as $index => $value) {
                    $value[$option] = $item;
                    $tmp[$index] = $value;
                }

                // 5、将完整的组合拼回原列表中
                $rows = array_merge($rows, $tmp);
            }
        } else {
            // 1、先计算出第一列
            foreach ($items as $item) {
                $rows[][$option] = $item;
            }
        }
    }

    return $rows;
}

/**
 * 多语言tab选择按钮
 */
function language_tab(){
    $language_array = config('language_array');
    if(!is_array($language_array))return '';
    $html = '<div class="language-btn"><ul>';
    foreach ($language_array as $k=>$v){
        $html .= '<li class="layui-btn '.($k!='cn'?'layui-btn-primary':'').'">'.$v.'</li>';
    }
    $html .= '</ul></div>';
    echo $html;
}




/**
 * 根据尺寸压缩图片
 * @param $url //图片的相对路径
 * @param $maxwidth //设置图片的最大宽度
 * @param $maxheight //设置图片的最大高度
 * @return array //图片压缩后路径
 */
function resizeImage($url,$maxwidth=0,$maxheight=0)
{
    $web = model('System')->getValue('upload_config');
    if($web['img_resize']=='on'){   //开启图片压缩后，上传后调整图片大小
        if(!extension_loaded('gd')){
            return ['error' => 1,'message' => '请开启gd扩展'];
        }
        /*if($maxwidth<1 || $maxheight<1){
            return ['error' => 1,'message' => '请设置图片最大宽高']; //ie10以下获取不到传参
        }*/
        //$file_name = substr($url,strripos($url,"/")+1);
        //$filetype = strtolower(substr($file_name,strripos($file_name,".")+1));  //后缀名
        //$name = substr($url,0,strrpos($url,".")).'_resize.';   //不含后缀的文件名
        $name = $url;//$name.$filetype;
        //1 = GIF，2 = JPG，3 = PNG，6 = BMP，15 = WBMP，16 = XBM。
        $type = getimagesize($url)[2];   //图片的类型，即使修改后缀

        //png图片直接返回原图路径，png透明图片会导致压缩后图片改变
        if($type==3)return ['error' => 0,'url' => ltrim($url,'.')];

        switch ($type){
            case 1:
                $im = imagecreatefromgif($url);
                break;
            case 2:
                $im = imagecreatefromjpeg($url);
                break;
            case 3:
                $im = imagecreatefrompng($url);
                break;
            case 15:
                $im = imagecreatefromwbmp($url);
                break;
            case 6:
                $im = $this->imagecreatefrombmp($url);
                break;
        }

        $pic_width = imagesx($im);
        $pic_height = imagesy($im);
        //开启推荐尺寸等比缩小，并且宽高有任一大于推荐尺寸才进行缩小
        if($web['img_resize_opt']==2 && (($maxwidth && $pic_width > $maxwidth) || ($maxheight && $pic_height > $maxheight)))
        {
            if($maxwidth && $pic_width>$maxwidth)
            {
                $widthratio = $maxwidth/$pic_width;
                $resizewidth_tag = true;
            }

            if($maxheight && $pic_height>$maxheight)
            {
                $heightratio = $maxheight/$pic_height;
                $resizeheight_tag = true;
            }

            if($resizewidth_tag && $resizeheight_tag)
            {
                if($widthratio<$heightratio)
                    $ratio = $widthratio;
                else
                    $ratio = $heightratio;
            }

            if($resizewidth_tag && !$resizeheight_tag)
                $ratio = $widthratio;
            if($resizeheight_tag && !$resizewidth_tag)
                $ratio = $heightratio;

            $newwidth = $pic_width * $ratio;
            $newheight = $pic_height * $ratio;

            if(function_exists("imagecopyresampled"))
            {
                $newim = imagecreatetruecolor($newwidth,$newheight);
                imagecopyresampled($newim,$im,0,0,0,0,$newwidth,$newheight,$pic_width,$pic_height);//PHP系统函数
            }
            else
            {
                $newim = imagecreate($newwidth,$newheight);
                imagecopyresized($newim,$im,0,0,0,0,$newwidth,$newheight,$pic_width,$pic_height);
            }

            switch ($type){
                case 1:
                    imagegif($newim,$name);
                    break;
                case 2:
                    imagejpeg($newim,$name);
                    break;
                case 3:
                    imagepng($newim,$name);
                    break;
                case 15:
                    imagewbmp($newim,$name);
                    break;
                default:
                    imagejpeg($newim,$name);
                    break;
            }
            imagedestroy($newim);
        }
        else
        {//仅压缩图片
            switch ($type){
                case 2:
                    imagejpeg($im,$name);
                    break;
                case 3:
                    imagepng($im,$name);
                    break;
                case 15:
                    imagewbmp($im,$name);
                    break;
                default:
                    imagejpeg($im,$name);
                    break;
            }
        }
        if(is_file($name)){
            return ['error' => 0,'url' => ltrim($name,'.')];
        }
    }
    //未开启图片压缩、压缩后无图片，等原因返回原图路径
    return ['error' => 0,'url' => ltrim($url,'.')];
}
/**
 * BMP imagecreatefrombmp函数需php7.2，创建函数
 * @param string $filename path of bmp file
 * @return resource of GD
 */
if(!function_exists("imagecreatefrombmp")) {
    function imagecreatefrombmp($filename)
    {
        if (!$f1 = fopen($filename, "rb"))
            return FALSE;

        $FILE = unpack("vfile_type/Vfile_size/Vreserved/Vbitmap_offset", fread($f1, 14));
        if ($FILE['file_type'] != 19778)
            return FALSE;

        $BMP = unpack('Vheader_size/Vwidth/Vheight/vplanes/vbits_per_pixel' . '/Vcompression/Vsize_bitmap/Vhoriz_resolution' . '/Vvert_resolution/Vcolors_used/Vcolors_important', fread($f1, 40));
        $BMP['colors'] = pow(2, $BMP['bits_per_pixel']);
        if ($BMP['size_bitmap'] == 0)
            $BMP['size_bitmap'] = $FILE['file_size'] - $FILE['bitmap_offset'];
        $BMP['bytes_per_pixel'] = $BMP['bits_per_pixel'] / 8;
        $BMP['bytes_per_pixel2'] = ceil($BMP['bytes_per_pixel']);
        $BMP['decal'] = ($BMP['width'] * $BMP['bytes_per_pixel'] / 4);
        $BMP['decal'] -= floor($BMP['width'] * $BMP['bytes_per_pixel'] / 4);
        $BMP['decal'] = 4 - (4 * $BMP['decal']);
        if ($BMP['decal'] == 4)
            $BMP['decal'] = 0;

        $PALETTE = array();
        if ($BMP['colors'] < 16777216) {
            $PALETTE = unpack('V' . $BMP['colors'], fread($f1, $BMP['colors'] * 4));
        }

        $IMG = fread($f1, $BMP['size_bitmap']);
        $VIDE = chr(0);

        $res = imagecreatetruecolor($BMP['width'], $BMP['height']);
        $P = 0;
        $Y = $BMP['height'] - 1;
        while ($Y >= 0) {
            $X = 0;
            while ($X < $BMP['width']) {
                if ($BMP['bits_per_pixel'] == 32) {
                    $COLOR = unpack("V", substr($IMG, $P, 3));
                    $B = ord(substr($IMG, $P, 1));
                    $G = ord(substr($IMG, $P + 1, 1));
                    $R = ord(substr($IMG, $P + 2, 1));
                    $color = imagecolorexact($res, $R, $G, $B);
                    if ($color == -1)
                        $color = imagecolorallocate($res, $R, $G, $B);
                    $COLOR[0] = $R * 256 * 256 + $G * 256 + $B;
                    $COLOR[1] = $color;
                } elseif ($BMP['bits_per_pixel'] == 24)
                    $COLOR = unpack("V", substr($IMG, $P, 3) . $VIDE);
                elseif ($BMP['bits_per_pixel'] == 16) {
                    $COLOR = unpack("n", substr($IMG, $P, 2));
                    $COLOR[1] = $PALETTE[$COLOR[1] + 1];
                } elseif ($BMP['bits_per_pixel'] == 8) {
                    $COLOR = unpack("n", $VIDE . substr($IMG, $P, 1));
                    $COLOR[1] = $PALETTE[$COLOR[1] + 1];
                } elseif ($BMP['bits_per_pixel'] == 4) {
                    $COLOR = unpack("n", $VIDE . substr($IMG, floor($P), 1));
                    if (($P * 2) % 2 == 0)
                        $COLOR[1] = ($COLOR[1] >> 4);
                    else
                        $COLOR[1] = ($COLOR[1] & 0x0F);
                    $COLOR[1] = $PALETTE[$COLOR[1] + 1];
                } elseif ($BMP['bits_per_pixel'] == 1) {
                    $COLOR = unpack("n", $VIDE . substr($IMG, floor($P), 1));
                    if (($P * 8) % 8 == 0)
                        $COLOR[1] = $COLOR[1] >> 7;
                    elseif (($P * 8) % 8 == 1)
                        $COLOR[1] = ($COLOR[1] & 0x40) >> 6;
                    elseif (($P * 8) % 8 == 2)
                        $COLOR[1] = ($COLOR[1] & 0x20) >> 5;
                    elseif (($P * 8) % 8 == 3)
                        $COLOR[1] = ($COLOR[1] & 0x10) >> 4;
                    elseif (($P * 8) % 8 == 4)
                        $COLOR[1] = ($COLOR[1] & 0x8) >> 3;
                    elseif (($P * 8) % 8 == 5)
                        $COLOR[1] = ($COLOR[1] & 0x4) >> 2;
                    elseif (($P * 8) % 8 == 6)
                        $COLOR[1] = ($COLOR[1] & 0x2) >> 1;
                    elseif (($P * 8) % 8 == 7)
                        $COLOR[1] = ($COLOR[1] & 0x1);
                    $COLOR[1] = $PALETTE[$COLOR[1] + 1];
                } else
                    return FALSE;
                imagesetpixel($res, $X, $Y, $COLOR[1]);
                $X++;
                $P += $BMP['bytes_per_pixel'];
            }
            $Y--;
            $P += $BMP['decal'];
        }
        fclose($f1);

        return $res;
    }
}

/**获取企业ID
 * @return string
 */
function get_appId(){
    return \think\Env::get("work.corpid");
//    return 'wwca4f9a0b128382c0';
}

/**获取自建应用密钥
 * @return string
 */
function get_appSecret(){
    return \think\Env::get("work.sceret");
//    return 'mA9Ia3mDzemwi0-hN0pYC_Wf6hPGAK1RYvib17jRbV0';
}

/**获取自建应用ID
 * @return string
 */
function get_agentid(){
    return \think\Env::get("work.agentid");
//    return '1000003';
}
function get_appSecretGzt(){
    return \think\Env::get("work.gztsecret");
//    return 'hHonjMMCfjMXEWwJSqZcyQRmJhpIyHXkv_k31ziaj08';
}
function get_agentid1(){
    return \think\Env::get("work.gztagentid");
//    return '1000007';
}

/**获取
 * @return mixed
 */
function get_access_token(){
    $accessToken = cache('access_token');
    if(!$accessToken){
        $url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid='.get_appId().'&corpsecret='.get_appSecret();
        $token = json_decode(httpGet($url),true);
        $data['access_token'] = $token['access_token'];
        $data['expires']=$token['expires_in']-200;
        cache('access_token',$data['access_token'],$data['expires']);
        return $data['access_token'];
    }else{
        return $accessToken;
    }
}
/**获取 工资条专属token
 * @return mixed
 */
function get_access_token1(){
    $accessToken = cache('access_token1');
    if(!$accessToken){
        $url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid='.get_appId().'&corpsecret='.get_appSecretGzt();
        $token = json_decode(httpGet($url),true);
        $data['access_token'] = $token['access_token'];
        $data['expires']=$token['expires_in']-200;
        cache('access_token1',$data['access_token'],$data['expires']);
    }else{
        return $accessToken;
    }
}
/**获取用户信息
 * @param $userid
 * @return mixed
 */
function get_user_info($userid){
    $data = model('user')->where('user_id','=',$userid)->find();
    return $data;
    $url = $get_userid_url = 'https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token='. get_access_token() . '&userid=' .$userid;
    $res = httpGet($url);
    $res= json_decode($res,true);
    return $res;
}
/**获取用户信息
 * @param $userid
 * @return mixed
 */
function get_user_info_new($userid){
    $url = $get_userid_url = 'https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token='. get_access_token() . '&userid=' .$userid;
    $res = httpGet($url);
    $res= json_decode($res,true);
    return $res;
}


/**获取部门列表
 * @return mixed
 */
function get_department_list(){
   $url = 'https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token='.get_access_token();
   $res= httpGet($url);
   $res = json_decode($res,true);
   return $res;
}
function get_department_list_id($id){
   $url = 'https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token='.get_access_token().'&id='.$id;
   $res= httpGet($url);
   $res = json_decode($res,true);
   return $res;
}
function get_department_list_id1($id){
    $url = 'https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token='.get_access_token1().'&id='.$id;
    $res= httpGet($url);
    $res = json_decode($res,true);
    return $res;
}

function get_user_list($id,$fe=1){
    $url = 'https://qyapi.weixin.qq.com/cgi-bin/user/simplelist?access_token='.get_access_token().'&department_id='.$id.'&fetch_child='.$fe;
    $res= httpGet($url);
    $res = json_decode($res,true);
    return $res;
}

/** 根据部门获取成员列表
 * @param $department_id
 * @param int $fetch_child
 * @return mixed
 */
function get_userlist_bydepartmentid($department_id,$fetch_child=1){
    $url = 'https://qyapi.weixin.qq.com/cgi-bin/user/list?access_token='.get_access_token().'&department_id='.$department_id.'&fetch_child='.$fetch_child;
    $res= httpGet($url);
    $res= json_decode($res,true);
    return $res;
}
function get_userlist_bydepartmentid1($department_id,$fetch_child=1){
    $url = 'https://qyapi.weixin.qq.com/cgi-bin/user/list?access_token='.get_access_token1().'&department_id='.$department_id.'&fetch_child='.$fetch_child;
    $res= httpGet($url);
    $res= json_decode($res,true);
    return $res;
}

/**获取js ticket
 * @return mixed
 */
function get_jsapi_ticket(){
    $url = 'https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token='.get_access_token();
    $res= httpGet($url);
    $res= json_decode($res,true);
    return $res;
}

/**
 * @param $touser
 * @param $title
 * @param $description
 * @param $url
 * @return mixed
 发送应用消息
 */
function send_message_templete($touser,$title,$description,$return){
    $url = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token='.get_access_token();
    $data=[
        "touser"=>implode('|',$touser),
        "msgtype"=>"textcard",
        "agentid"=>get_agentid(),
        "textcard"=>[
            "title"=>$title,
            "description"=>$description,
            "url"=>$return,
            "btntxt"=>"详情"
        ],
		'enable_duplicate_check'=>1,
		'duplicate_check_interval'=>1440
    ];
    $data = json_encode($data);
    $res= httpPost($url,$data);
    $res= json_decode($res,true);
    return $res;

}
function send_message_templete1($touser,$title,$description,$return){
    $url = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token='.get_access_token1();
    $data=[
        "touser"=>implode('|',$touser),
        "msgtype"=>"textcard",
        "agentid"=>get_agentid1(),
        "textcard"=>[
            "title"=>$title,
            "description"=>$description,
            "url"=>$return,
            "btntxt"=>"详情"
        ]
    ];
    $data = json_encode($data);
    $res= httpPost($url,$data);
    $res= json_decode($res,true);
    return $res;

}
/**评论是否点赞
 * @param $comment_id
 * @return bool
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 */
function is_comment_appreciate($comment_id){
    $comment_appreciate = new \app\index\model\Commentappreciate();
    $info = $comment_appreciate->where(['user_id'=>session('user_info')['userid'],'comment_id'=>$comment_id])->find();
    if($info){
        return true;
    }
    return false;
}

/**
 * 数组转xls格式的excel文件
 * @param  array  $data      需要生成excel文件的数组
 * @param  string $filename  生成的excel文件名
 *      示例数据：
$data = array(
array(NULL, 2010, 2011, 2012),
array('Q1',   12,   15,   21),
array('Q2',   56,   73,   86),
array('Q3',   52,   61,   69),
array('Q4',   30,   32,    0),
);
 */
function create_xls($data,$filename='salary.xlsx'){
    ini_set('max_execution_time', '0');
    Vendor('PHPExcel.PHPExcel');
    $filename=str_replace('.xlsx', '', $filename).'.xlsx';
    $phpexcel = new PHPExcel();
    $phpexcel->getProperties()
        ->setCreator("Maarten Balliauw")
        ->setLastModifiedBy("Maarten Balliauw")
        ->setTitle("Office 2007 XLSX Test Document")
        ->setSubject("Office 2007 XLSX Test Document")
        ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
        ->setKeywords("office 2007 openxml php")
        ->setCategory("Test result file");
    $phpexcel->getActiveSheet()->fromArray($data);
    $phpexcel->getActiveSheet()->setTitle('Sheet1');
    $phpexcel->setActiveSheetIndex(0);
    header('Content-Type: application/vnd.ms-excel');
    header("Content-Disposition: attachment;filename=$filename");
    header('Cache-Control: max-age=0');
    header('Cache-Control: max-age=1');
    header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
    header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
    header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
    header ('Pragma: public'); // HTTP/1.0
    $objwriter = PHPExcel_IOFactory::createWriter($phpexcel, 'Excel2007');
    $objwriter->save('php://output');
    exit;
}
/*
* 过滤emoji函数
*/
function filterEmoji($str)
{
    $str = preg_replace_callback('/./u',
        function (array $match) {
            return strlen($match[0]) >= 4 ? '' : $match[0];
        },
        $str);
    return $str;
}

function getAvatar($value)
{
    if(!$value){
       $value = '/public/static/index/images/unknowavatar.jpg';
    }
    return $value;

}

